package com.hongluan.love.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.util.Log;

import com.lidroid.xutils.util.LogUtils;

public class ImageUtil
{
	private static Options m_options;

	public static Bitmap getBitmap(String fileName, int resize)
	{
		Bitmap res = null;
		if (fileName != null) {
			File f = new File(fileName);
			if (f.exists()) {
				if (m_options == null) {
					m_options = new Options();
					m_options.inPurgeable = true;
					m_options.inPreferredConfig = Config.RGB_565;
				}
				m_options.inSampleSize = resize;
				try {
					res = BitmapFactory.decodeFile(fileName, m_options);
				} catch (OutOfMemoryError e) {
					LogUtils.e("decode file oom" + fileName);
				}

				if (res == null) {
					LogUtils.d("decode file " + fileName + " failed.");
				}
			} else {
				LogUtils.d("decode iamge " + fileName + " not exists.");
			}
		}
		return res;
	}

	public static Bitmap getBitmap(String fileName)
	{
		return getBitmap(fileName, 1);
	}

	public static void save(Bitmap bitmap, String fileName)
	{
		if (bitmap != null && fileName != null) {
			File f = new File(fileName);
			try {
				if (!f.exists()) {
					if (!f.createNewFile()) {
						LogUtils.e("create file failed: " + fileName);
					}
				}
				LogUtils.d("save to " + fileName);
				FileOutputStream fOut = new FileOutputStream(f);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
				fOut.flush();
				fOut.close();
			} catch (FileNotFoundException e) {
				LogUtils.e(Log.getStackTraceString(e));
			} catch (IOException e) {
				LogUtils.e(Log.getStackTraceString(e));
			}
		}
	}
}
